<template>
  <view
    class="app-page"
    :style="fileLoadendCount >= 2 ? '' : 'overflow-y:hidden;'"
  >
    <container v-if="fileLoadendCount < 2" class="container">
      <skeleton :paragraph="paragraph" class="skeleton" :animate="true" />
    </container>
    <view class="pager">
      {{ pageNo }}/{{ info.contractSignatureUrl.length || 1 }}
    </view>
    <view class="file-content">
      <view v-for="(item, index) in info.contractSignatureUrl" :key="index">
        <image class="pdf" mode="widthFix" :src="item" onLoad="onFileLoad" />
      </view>
      <view
        v-if="
          fileLoadendCount &&
          roleType == 0 &&
          info.contractState == 1 &&
          !info.creditorMemberSignatureId
        "
        :class="{ role0SignP: true, addsign: signUrl }"
        data-role="0"
        @click="handleGoSign"
      >
        <image
          a:if=" signUrl "
          class="signUrl"
          mode="widthFix"
          :src="signUrl"
        />
      </view>
      <view
        v-if="
          fileLoadendCount &&
          roleType == 1 &&
          info.contractState == 1 &&
          !info.debtorMemberSignatureId
        "
        :class="{ role1SignP, addsign: signUrl }"
        data-role="1"
        @click="handleGoSign"
      >
        <image v-if="signUrl" class="signUrl" mode="widthFix" :src="signUrl" />
      </view>
    </view>

    <!-- 签署中-->
    <view
      v-if="roleType === 2 || info.contractState >= 2"
      class="footer safe-area"
    >
      <button class="signBtn" @click="handleBackToPrev">返回</button>
    </view>
    <view v-else-if="info.contractState === 1" class="footer safe-area">
      <view
        class="caAgree"
        @click.stop="onReadCa"
        v-if="
          (roleType === 0 && !info.creditorMemberSignatureId) ||
          (roleType === 1 && !info.debtorMemberSignatureId)
        "
      >
        <image v-if="readCa" class="agreeRadio" src="@/static/images/check.png" />
        <image
          v-else-if="!readCa"
          class="agreeRadio"
          src="@/static/images/nocheck.png"
        />
        我已阅读并同意
        <text @click.stop="onViewCa">《电子认证服务协议》</text>
      </view>
      <button
        v-if="
          !signUrl &&
          ((roleType === 0 && !info.creditorMemberSignatureId) ||
            (roleType === 1 && !info.debtorMemberSignatureId))
        "
        class="signBtn"
        @click="handleGoSign"
      >
        进行电子签名
      </button>
      <button
        v-else-if="
          signUrl &&
          ((roleType === 0 && !info.creditorMemberSignatureId) ||
            (roleType === 1 && !info.debtorMemberSignatureId))
        "
        class="signBtn"
        @click="handleSubmit"
      >
        签署文件
        <!-- 提交签字/盖章 -->
      </button>
    </view>
    <view
      v-else-if="info.contractState === 0 && mode === 'cache'"
      class="footer safe-area"
    >
      <button class="btn" type="default" @click="handleBackToEdit">
        返回修改
      </button>
      <button class="btn" type="primary" @click="handleSend">发起借条</button>
    </view>

    <!-- 使用须知弹层 -->
    <uni-popup
      ref="useNoticeRefs"
      class="notice-popup"
      visible="{{ useNoticeShow }}"
      type="bottom"
      @close="onNoticeOpenClose"
    >
      <view class="notice-content safe-area">
        <uni-icons
          class="notice-close"
          type="CloseOutline"
          @click="onNoticeOpenClose"
        >
        </uni-icons>
        <view class="notice-title">
          {{ articleInfo.title }}
        </view>
        <scroll-view
          scroll-y
          class="notice-view"
          disable-lower-scroll="out-of-bounds"
          disable-upper-scroll="out-of-bounds"
        >
          <rich-text :nodes="articleInfo.content" @click="tap"></rich-text>
        </scroll-view>
        <view>
          <ant-button @click="onAgreeNotice" class="notice-btn">
            我已理解并接受上述内容
          </ant-button>
        </view>
      </view>
    </uni-popup>
    <!-- 使用须知弹层 -->

    <!-- 签字版 -->
    <sign-board
      v-if="signShow"
      ref="signBoardRefs"
      @save="handleSignToImg"
      @cancel="handleSignCancel"
    >
    </sign-board>
    <!-- 签字版 -->
    <!-- 购买签署流量弹层 -->
    <pay-flow ref="payFlowRefs" @pay="handlePayFlow" />
    <!-- 购买签署流量弹层 -->
  </view>
</template>

<script>
import { upload } from "@/utils/common";
import {
  apiContractById,
  apiCreateContract,
  apiMemberSignatureAdd,
  apiPreview,
  apiGetContractInfoCache,
  apiSigning,
  apiExpiringSoonOne,
  apiMemberSignPackagePay,
  apiArticleById,
  apiGetCA,
} from "@/api/common";

import code2Enum from "@/utils/code2Enum";
export default {
  components: {},
  data() {
    return {
      fileHeight: 0,
      signShow: false,
      info: {
        contractSignatureUrl: [],
      },
      caInfo: {
        agreementUrl: "",
        orderNumber: "",
      },
      pageNo: 1,
      readCa: false,
      userType: "into", //into 合同双方  other 第三方
      useNoticeShow: false, //使用须知
      signToolShow: false, //签章工具弹层
      signTool: "handle", //当前选择得签章类型
      signInAll: false, //签章是否盖在所有签署区
      signUrl: "", //签字版图片
      signatureId: "",
      contractId: {},
      mode: "", //cache 缓存
      roleType: 3, //0  出借方  1  借款方  2 第三方
      fileLoadendCount: 0,
      paragraph: {
        rows: 12,
      },
      articleInfo: {
        title: "",
        content: "",
      },
    };
  },

  onLoad(query) {
    uni.hideShareMenu();
    this.getArticle();
    this.getCaAgree();
    console.log(query, "query");
    const { contractId, mode, roleType } = query;
    this.mode = mode;
    this.contractId = contractId;
    this.$nextTick(() => {
      if (mode === "cache") {
        this.getCacheData();
      } else {
        this.getData();
      }
    });
  },
  onPageScroll(e) {
    const { scrollTop } = e;
    const { info, fileHeight } = this;
    let num = Math.ceil(
      scrollTop / (fileHeight / info.contractSignatureUrl.length / 2)
    );
    if (num < 1) {
      num = 1;
    } else if (num > info.contractSignatureUrl.length) {
      num = Math.min(num, info.contractSignatureUrl.length);
    }
    this.pageNo = num;
  },
  methods: {
    getCaAgree() {
      apiGetCA().then((res) => {
        if (res.code === 200) {
          console.log(res);
          this.caInfo = res.data.data;
        }
      });
    },
    onReadCa() {
      this.readCa = !this.readCa;
    },
    onViewCa() {
      uni.downloadFile({
        url: this.caInfo.agreementUrl, // 示例 url，并非真实存在
        success(res) {
          uni.openDocument({
            filePath: res.apFilePath,
            fileType: "pdf",
          });
        },
      });
    },
    getArticle() {
      apiArticleById({
        articleIdList: 4,
      }).then((res) => {
        if (res.code === 200 && res.data && res.data.length > 0) {
          this.articleInfo = {
            id: 4,
            title: res.data[0].articleTitle,
            content: res.data[0].articleDetails,
          };
        }
      });
    },
    getCachePreview(params) {
      const _this = this;
      apiPreview(params).then((res) => {
        if (res.code === 200) {
          (this.info = {
            ...this.info,
            contractSignatureUrl: res.data.base64Content.map((item) => {
              return "data:image/jpeg;base64," + item;
            }),
          }),
            this.$nextTick(() => {
              uni
                .createSelectorQuery()
                .select(".file-content")
                .boundingClientRect()
                .exec((res) => {
                  const height = res[0].height;
                  _this.fileHeight = height;
                });
            });
        }
      });
    },
    getCacheData() {
      const { contractId } = this;
      apiGetContractInfoCache({
        cacheKey: contractId,
      }).then((res) => {
        if (res.code === 200) {
          const { creditorMember, debtorMember } = res.data;
          const memberId = this.$store.state.userInfo.memberId;
          this.info = {
            ...res.data,
            contractState: 0,
            contractSignatureUrl: res.data.contractSignatureUrl
              ? res.data.contractSignatureUrl.split(",")
              : "",
          };
          this.roleType =
            memberId === creditorMember ? 0 : memberId === debtorMember ? 1 : 2; //0 出借 1 借款 3 其他
          this.$nextTick(() => {
            this.getCachePreview(res.data);
          });
        }
      });
    },
    getData() {
      const _this = this;
      const { contractId } = this;
      apiContractById({
        contractId: contractId,
      }).then((res) => {
        if (res.code === 200) {
          res.data = {
            ...res.data,
            contractState: code2Enum.contractStateEnum(res.data.contractState),
            promoterType: code2Enum.promoterTypeEnum(res.data.promoterType),
            contractPayState: code2Enum.contractPayStateEnum(
              res.data.contractPayState
            ),
            paymentType: code2Enum.paymentTypeEnum(res.data.paymentType),
            transferStatus: code2Enum.transferStatusEnum(
              res.data.transferStatus
            ),
          };
          const { creditorMember, debtorMember } = res.data;
          const memberId = _this.$store.state.userInfo.memberId;
          _this.info = {
            ...res.data,
            contractSignatureUrl: res.data.contractSignatureUrl.split(","),
          };
          _this.roleType =
            memberId === creditorMember ? 0 : memberId === debtorMember ? 1 : 2; //0 出借 1 借款 3 其他
          _this.$nextTick(() => {
            uni
              .createSelectorQuery()
              .select(".file-content")
              .boundingClientRect()
              .exec((res) => {
                const height = res[0].height;
                _this.fileHeight = height;
              });
          });
        }
      });
    },
    handleBackToPrev() {
      uni.navigateBack({
        fail: function () {
          uni.reLaunch({
            url: "/pages/home/index",
          });
        },
      });
    },
    // 合同双方---返回修改
    handleBackToEdit() {
      uni.navigateBack();
    },
    // 合同双方---发起借条--检查支付

    async handleSend() {
      this.onNoticeOpenClose();
    },
    // 检查支付
    checkPayAfterSend(params) {
      const _this = this;
      const { roleType } = _this;
      //未支付
      // 查询是否存在未使用得流量包
      apiExpiringSoonOne().then((res) => {
        if (res.code === 200) {
          const memberSignPackageId = res.data
            ? res.data.memberSignPackageId
            : null;
          // 出借方可选择对方付款
          if (roleType === 0) {
            // 有剩余流量包
            if (memberSignPackageId) {
              uni.showModal({
                title: "提示",
                content: "是否使用流量包支付？",
                cancelText: "我来付",
                cancelColor: "#333",
                confirmText: "让对方付",
                showCancel: true,
                success: function (res) {
                  if (res.confirm) {
                    apiCreateContract({
                      ..._this.info,
                    }).then((res) => {
                      if (res.code === 200) {
                        uni.redirectTo({
                          url: `/pages/fileState/fileState?contractId=${res.data.contractId}`,
                        });
                      }
                    });
                  } else {
                    _this.signPackagePay(memberSignPackageId);
                  }
                },
                fail: function (err) {
                  console.log(err);
                },
              });
            } else {
              // 没有剩余流量包 唤起支付购买
              uni.showModal({
                title: "提示",
                content: "是否支付借条费用？",
                cancelText: "我来付",
                cancelColor: "#333",
                confirmText: "让对方付",
                showCancel: true,
                success: function (res) {
                  if (res.confirm) {
                    //让对方付
                    apiCreateContract({
                      ..._this.info,
                    }).then((res) => {
                      if (res.code === 200) {
                        uni.reLaunch({
                          url: `/pages/fileState/fileState?contractId=${res.data.contractId}`,
                        });
                      }
                    });
                  } else {
                    //我来付
                    // my.showToast({
                    //   content: '余额不足，请充值',
                    //   icon: 'none',
                    //   duration: 2000,
                    //   mask: true
                    // })
                    // setTimeout(() => {
                    uni.hideToast();
                    _this.$refs.payFlowRefs.handleOpen();
                    // }, 2000)
                  }
                },
              });
            }
          } else {
            // 借款方必须支付
            // 有剩余流量包
            if (memberSignPackageId) {
              uni.showModal({
                title: "提示",
                content: "是否使用流量包支付？",
                cancelText: "取消",
                cancelColor: "#333",
                confirmText: "确认",
                showCancel: true,
                success: function (res) {
                  if (res.confirm) {
                    _this.signPackagePay(memberSignPackageId);
                  }
                },
                fail: function (err) {
                  console.log(err);
                },
              });
            } else {
              // 没有剩余流量包 唤起支付购买
              // my.showToast({
              //   content: '余额不足，请充值',
              //   icon: 'none',
              //   duration: 2000
              // })
              // setTimeout(() => {
              uni.hideToast();
              _this.$refs.payFlowRefs.handleOpen();
              // }, 2000)
            }
          }
        }
      });
    },
    // 展示、关闭---使用须知
    onNoticeOpenClose() {
      this.$refs.useNoticeRefs.open();
    },
    // ---使用协议
    onAgreeNotice() {
      this.$refs.useNoticeRefs.close();
      this.$nextTick(() => {
        this.checkPayAfterSend();
      });
    },
    // 立即购买流量
    handlePayFlow() {
      // TODO
      const { contractId } = this;
      // 查询是否存在未使用得流量包
      apiExpiringSoonOne().then((res) => {
        if (res.code === 200) {
          const memberSignPackageId = res.data
            ? res.data.memberSignPackageId
            : null;
          memberSignPackageId && this.signPackagePay(memberSignPackageId);
        }
      });
    },
    // 支付合同
    signPackagePay(memberSignPackageId) {
      this.$refs.payFlowRefs.handleClose();
      apiCreateContract({
        ...this.info,
      }).then((res) => {
        if (res.code === 200) {
          apiMemberSignPackagePay({
            contactInfoId: res.data.contractId,
            memberSignPackageId,
          }).then((result) => {
            if (result.code === 200) {
              uni.reLaunch({
                url: `/pages/fileState/fileState?contractId=${res.data.contractId}`,
              });
            }
          });
        }
      });
    },

    // 流量购买---服务协议阅读
    handleReadChange(e) {
      console.log(e, "handleReadChange");
      uni.navigateTo({
        url: `/pages/article/article?type=serviceAgree&id=5`,
      });
    },

    // 展示/关闭 选择签章弹层
    handleSignToolClose() {
      this.$refs.signBoardRefs.open();
    },
    // // 切换签章类型
    // handleChangeTool(e) {
    //   const { type } = e.target.dataset
    //   this.setData({
    //     signTool: type
    //   }, () => {
    //     if (type === 'handle') {
    //       this.handleGoSign()
    //     }
    //   })
    // },
    onFileLoad(e) {
      this.fileLoadendCount += 1;
    },
    // 显示签字版
    handleDisabled() {
      uni.showToast({
        content: "签字后才能签署文件！",
      });
    },
    // 开始手签
    handleGoSign(e) {
      this.$refs.signBoardRefs.handleOpen();
    },
    // 签字板取消
    handleSignCancel() {},
    // 签字版导出图片
    handleSignToImg(signUrl) {
      upload(signUrl)
        .then((resUrl) => {
          console.log("签字版导出图片:resUrl", resUrl);
          this.signUrl = resUrl;
        })
        .catch((err) => {
          uni.showToast({
            content: err,
          });
        });
    },
    // 提交签字/盖章
    handleSubmit() {
      if (!this.readCa) {
        muniy.showToast({
          content: "请阅读并同意《电子认证服务协议》",
        });
        return false;
      }
      apiMemberSignatureAdd({
        memberSignaturePath: this.signUrl,
      }).then((res) => {
        if (res.code === 200) {
          const memberSignatureId = res.data.memberSignatureId;
          const { roleType, contractId, caInfo } = this;
          this.signatureId = memberSignatureId;
          this.$store.dispatch("ASYNC_FACE", () => {
            // 人脸校验后签署
            apiSigning({
              signType: roleType,
              memberSignatureId,
              contractId: contractId,
              certOrderNumber: caInfo.orderNumber,
            })
              .then((result) => {
                if (result.code === 200 && result.data) {
                  uni.showToast({
                    content: "签署成功",
                    mask: true,
                  });
                  // setTimeout(() => {
                  uni.hideToast();
                  uni.reLaunch({
                    url: `/pages/signSuccess/signSuccess?contractId=${contractId}&roleType=${roleType}`,
                  });
                  // }, 3000)
                }
              })
              .catch((err) => {});
          });
        }
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.app-page {
  min-height: 100vh;
  box-sizing: border-box;
  padding-top: 20rpx;
}

.pager {
  width: 90rpx;
  height: 40rpx;
  background: #7f7f7f;
  border-radius: 4rpx;
  font-size: 30rpx;
  font-family: PingFangSC, PingFang SC;
  color: #ffffff;
  line-height: 40rpx;
  position: fixed;
  top: 0;
  right: 48rpx;
  text-align: center;
  z-index: 2;
}
.container {
  width: 100%;
  height: 100vh;
  position: fixed;
  left: 0;
  top: 0;
  z-index: 22;
}
.skeleton {
  margin-bottom: 50rpx;
}
.file-content {
  width: 710rpx;
  margin: 0 20rpx;
  padding-bottom: 270rpx;
  position: relative;
}

.file-content .pdf {
  width: 100%;
}

.file-content .role0SignP {
  width: 180rpx;
  height: 180rpx;
  border: 3rpx solid #fb6411;
  position: absolute;
  left: 140rpx;
  top: 1220rpx;
}

.file-content .role1SignP {
  width: 180rpx;
  height: 180rpx;
  border: 3rpx solid #fb6411;
  position: absolute;
  left: 400rpx;
  top: 1220rpx;
}

.file-content .addsign {
  position: absolute;
}

.file-content .addsign::after {
  width: 100rpx;
  height: 100rpx;
  content: "";
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  background-image: url(@/static/images/addsign.png);
  background-size: cover;
  background-repeat: no-repeat;
}

.file-content .signUrl {
  width: 100%;
  margin-top: 50%;
  transform: translateY(-50%);
}

/* 使用须知弹层 */
.notice-content {
  position: relative;
}

.notice-view {
  width: 100vw;
  padding: 24rpx 24rpx 0;
  box-sizing: border-box;
  height: 888rpx;
}

.notice-close {
  width: 36rpx;
  height: 36rpx;
  font-size: 26rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  position: absolute;
  right: 24rpx;
  top: 24rpx;
}

.notice-title {
  height: 50rpx;
  font-size: 36rpx;
  font-family: PingFangSC, PingFang SC;
  font-weight: 500;
  color: #333333;
  line-height: 50rpx;
  font-weight: bold;
  text-align: center;
  border-bottom: 1rpx solid #eeeeee;
  padding: 24rpx;
}

.notice-btn {
  width: 702rpx;
  height: 98rpx;
  font-size: 36rpx;
  font-family: PingFangSC, PingFang SC;
  font-weight: 400;
  color: #ffffff;
  line-height: 50rpx;
  background: #1677ff;
  border-radius: 8rpx;
  margin-top: 108rpx;
  margin-left: 24rpx;
  margin-bottom: 24rpx;
}

/* 使用须知弹层 */

/* 底部按钮 */
.caAgree {
  width: 100%;
  display: flex;
  align-items: center;
  font-size: 24rpx;
  margin-bottom: 20rpx;
  padding-left: 24rpx;
}
.caAgree text {
  color: #1677ff;
}
.agreeRadio {
  width: 32rpx;
  height: 32rpx;
  margin-right: 20rpx;
}
.footer {
  width: 100%;
  background-color: #fff;
  padding: 24rpx 24rpx 24rpx;
  box-sizing: border-box;
  display: flex;
  align-items: center;
  justify-content: space-between;
  flex-wrap: wrap;
  position: fixed;
  left: 0;
  bottom: 24rpx;
}

.footer::after {
  width: 100%;
  height: 40rpx;
  content: "";
  position: absolute;
  left: 0;
  bottom: -32rpx;
  background-color: #fff;
}

.footer .btn {
  flex: 1;
  margin-right: 24rpx;
  margin-bottom: 24rpx;
}

.footer .btn:last-child {
  margin-right: 0;
}

.footer .signBtn {
  width: 654rpx;
  height: 98rpx;
  font-size: 36rpx;
  font-family: PingFangSC, PingFang SC;
  font-weight: bold;
  color: #ffffff;
  line-height: 98rpx;
  background: linear-gradient(180deg, #fa5a02 0%, #ff8441 60%, #fb5901 100%);
  border-radius: 49rpx;
  text-align: center;
  outline: 0;
  box-shadow: none;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: auto;
}

.disabled-btn {
  opacity: 0.4;
}

/* 底部按钮 */

/* 使用须知弹层 */
.signTool {
  position: relative;
}

.signTool-title {
  height: 50rpx;
  font-size: 36rpx;
  font-family: PingFangSC, PingFang SC;
  font-weight: bold;
  color: #333333;
  line-height: 50rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 30rpx 54rpx 24rpx 24rpx;
}

.current-signTool {
  width: 702rpx;
  font-size: 30rpx;
  font-family: PingFangSC, PingFang SC;
  color: #333333;
  line-height: 42rpx;
  padding-bottom: 24rpx;
  border-bottom: 1rpx solid #eeeeee;
  padding: 0 0 24rpx;
  box-sizing: border-box;
  margin: auto;
}

.tools {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 24rpx;
  box-sizing: border-box;
}

.tool-li {
  width: 331rpx;
  height: 232rpx;
  background: #f6f6f6;
  border-radius: 16rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 48rpx 0 38rpx;
  color: #999999;
  box-sizing: border-box;
  border: 4rpx solid #f6f6f6;
}

.tool-li.current {
  width: 331rpx;
  height: 232rpx;
  background: #ffffff;
  border-radius: 16rpx;
  border: 4rpx solid #fb6411;
  color: #fb6411;
  box-sizing: border-box;
}

.tool-li .tool-img {
  width: 80rpx;
  height: 80rpx;
  margin-bottom: 24rpx;
}

.tool-li text {
  height: 50rpx;
  font-size: 36rpx;
  font-family: PingFangSC, PingFang SC;
  font-weight: bold;
  line-height: 50rpx;
}

.signTool-btn {
  width: 654rpx;
  height: 98rpx;
  font-size: 36rpx;
  font-family: PingFangSC, PingFang SC;
  font-weight: bold;
  color: #ffffff;
  line-height: 50rpx;
  background: linear-gradient(180deg, #fa5a02 0%, #ff8441 60%, #fb5901 100%);
  border-radius: 49rpx;
  margin: 64rpx 48rpx 24rpx;
  outline: none;
  border: none;
  box-shadow: none;
}

/* 使用须知弹层 */
</style>
